package cn.ronghuanet.org.service.impl;

import cn.ronghuanet.base.service.impl.BaseServiceImpl;
import cn.ronghuanet.org.domain.Department;
import cn.ronghuanet.org.mapper.DepartmentMapper;
import cn.ronghuanet.org.service.IDepartmentService;
import cn.ronghuanet.base.utils.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public void save(Department department) {
        //维护path路径
        /*
            1.新增 用户会选择一个parent 或者为null
            2.如果父级部门有值 查询父级部门

         */
        departmentMapper.save(department);
        department.setCreate_time(new Date());
        if (department.getParent()==null){
            department.setPath("/"+department.getId());
        }else {
            Department parent = departmentMapper.queryById(department.getParent().getId());
            department.setPath(parent.getPath()+"/"+department.getId());
        }
        departmentMapper.update(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        if (department.getParent()==null){
            department.setPath("/"+department.getId());
        }else {
            Department parent = departmentMapper.queryById(department.getParent().getId());
            department.setPath(parent.getPath()+"/"+department.getId());
        }
        departmentMapper.update(department);
    }



    //加载部门树
    @Override
    public List<Department> queryDeptTree() {
        return departmentMapper.queryDeptTree();
    }
}
